# -*- coding: utf-8 -*-
import random

from info.api.ZTCCLOUD import ZTCCLOUD
from info.utils import utils

from utils import dbUtils


class BusinessData(ZTCCLOUD):

    def create_claim_flow_summary(self, **kwargs):
        """
        创建流水(收款/收票/扣款)
        """
        method_name = "创建流水(收款/收票/扣款)"
        msg = ''
        numdas = 1
        try:
            try:
                cookie = kwargs.get("cookie")
                base_url = kwargs.get("server_addr")
                user_addr = kwargs.get("user_addr")
                r_num = kwargs.get("run_num").strip("^").split("^")
                while len(r_num) < 4:
                    r_num.append(0)
                num_makeing = abs(int(r_num[0]))  # 创建发票的数量
                namedFlag = f"{kwargs.get('named_pre')}" if kwargs.get('named_pre') else ""  # 每笔数据的标记
                if num_makeing <= 0:
                    return f"{method_name} 字段值异常，造数数量需为正整数"
            except:
                return f"{method_name} 字段值异常，造数数量需为正整数"

            # 循环新增流水
            for _ in range(num_makeing):
                dirFlag = random.choice(["IN", "BILL_IN", "OUT"])
                # 查收款方/付款方银行账户信息
                isPayInfo = (dirFlag, "Y" if dirFlag == "OUT" else "N")
                receiptResp = self.claimflowsummary_queryBankAccountNew(base_url, cookie, *isPayInfo)
                receiptInfoList = receiptResp.get("page").get("list")
                receiptInfo = random.choice(receiptInfoList)
                if dirFlag in ("IN", "OUT"):
                    # 查付款方/收款方银行账户信息
                    isPayInfo2 = (dirFlag, receiptInfo.get("leId"), "Y" if dirFlag == "IN" else "N")
                    payResp = self.vendors_listLeIdAndBank(base_url, cookie, *isPayInfo2)
                    payInfoList = payResp.get("page").get("list")
                    if dirFlag == "OUT":
                        payInfoList, receiptInfoList = receiptInfoList, payInfoList
                else:
                    payInfoList = [{}]
                flag = False
                while payInfoList and receiptInfoList:
                    receiptInfo = random.choice(receiptInfoList)
                    payInfo = random.choice(payInfoList)
                    resp = self.claimflowsummary(base_url, cookie, **{
                        "receiptInfo": receiptInfo,
                        "payInfo": payInfo,
                        "dataPre": namedFlag,
                        "dirflag": dirFlag
                    })
                    if resp.get("msg") == "success":
                        flag = True
                        break
                    elif "收款方开户行无效或不存在" in resp.get("msg"):
                        receiptInfoList.remove(receiptInfo)
                    elif "付款方开户行无效或不存在" in resp.get("msg"):
                        payInfoList.remove(payInfo)
                    else:
                        msg = resp.get("msg")
                if flag:
                    utils.set_cache(base_url, user_addr, utils.get_func_name())
                    numdas += 1
                else:
                    if not msg:
                        msg = "100个开户行均无效，无法创建流水"
                    return msg
            if numdas >= num_makeing:
                msg = f"{method_name}完成，共【{numdas - 1}】条"
            else:
                dbUtils.write_data_to_db(kwargs.get("task_id"), user_addr, base_url)
                msg = f"{method_name}，已完成【{numdas - 1}】条，未完成【{num_makeing - numdas + 1}】条，原因：自己看【{base_url}】服务器日志"
            return msg
        except Exception as e:
            return f"{msg}\n{e}"

    def create_contract(self, **kwargs):
        """
        创建合同
        """
        method_name = "创建合同"
        msg = ''
        numdas = 1
        try:
            try:
                cookie = kwargs.get("cookie")
                base_url = kwargs.get("server_addr")
                user_addr = kwargs.get("user_addr")
                r_num = kwargs.get("run_num").strip("^").split("^")
                while len(r_num) < 4:
                    r_num.append(0)
                num_makeing = abs(int(r_num[0]))  # 创建发票的数量
                namedFlag = f"{kwargs.get('named_pre')}" if kwargs.get('named_pre') else ""  # 每笔数据的标记
                if num_makeing <= 0:
                    return f"{method_name} 字段值异常，造数数量需为正整数"
            except:
                return f"{method_name} 字段值异常，造数数量需为正整数"

            # 初始化合同
            initObj = self.contract_addInitialData(base_url, cookie)
            # 获取客商信息
            resp = self.vendors_listAndBank(base_url, cookie)
            vendorList = resp.get("page").get("list")
            # 获取项目信息
            resp = self.project_pageCollection(base_url, cookie)
            prjList = resp.get("page").get("list")

            # 循环新增合同
            for _ in range(num_makeing):
                # 客商信息
                vendorObj = random.choices(vendorList, k=random.randint(1, len(vendorList)))
                prjObj = random.choice(prjList)
                for _ in range(10):
                    resp = self.ldgcontract_submitContract(base_url, cookie, *(initObj, prjObj, vendorObj),
                                                           **{"dataPre": namedFlag})
                    if "success" in resp.get("msg"):
                        utils.set_cache(base_url, user_addr, utils.get_func_name())
                        numdas += 1
                        break
                    elif _ == 9:
                        return f"{method_name}新增失败，接口响应如下：\n{resp}"
            if numdas >= num_makeing:
                msg = f"{method_name}完成，共【{numdas - 1}】条"
            else:
                dbUtils.write_data_to_db(kwargs.get("task_id"), user_addr, base_url)
                msg = f"{method_name}，已完成【{numdas - 1}】条，未完成【{num_makeing - numdas + 1}】条，原因：自己看【{base_url}】服务器日志"
            return msg
        except Exception as e:
            return f"{msg}\n{e}"

    def create_invoice(self, **kwargs):
        """
        创建发票
        """
        method_name = "创建发票"
        msg = ''
        numdas = 1
        try:
            try:
                cookie = kwargs.get("cookie")
                base_url = kwargs.get("server_addr")
                user_addr = kwargs.get("user_addr")
                r_num = kwargs.get("run_num").strip("^").split("^")
                while len(r_num) < 4:
                    r_num.append(0)
                num_makeing = abs(int(r_num[0]))  # 创建发票的数量
                namedFlag = f"{kwargs.get('named_pre')}" if kwargs.get('named_pre') else ""  # 每笔数据的标记
                if num_makeing <= 0:
                    return f"{method_name} 字段值异常，造数数量需为正整数"
            except:
                return f"{method_name} 字段值异常，造数数量需为正整数"

            # 查发票模板信息
            resp = self.ticketdefine_list(base_url, cookie)
            result = list({
                              "billTypeInvoice": i.get("ticketType"),
                              "ticketDefineTemplateId": i.get("id"),
                              "dataPre": namedFlag
                          }
                          for i in resp.get("list") if i.get("ticketType") in ("3", "21", "17"))

            # 循环新增发票
            for _ in range(num_makeing):
                invoiceConfig = random.choice(result)
                for _ in range(10):
                    resp = self.boe_invoice_ticket_save(base_url, cookie, **invoiceConfig)
                    if "success" in resp.get("msg"):
                        utils.set_cache(base_url, user_addr, utils.get_func_name())
                        numdas += 1
                        break
                    elif _ == 9:
                        return f"{method_name}新增失败，接口响应如下：\n{resp}"
            if numdas >= num_makeing:
                msg = f"新增发票完成，共【{numdas - 1}】条"
            else:
                dbUtils.write_data_to_db(kwargs.get("task_id"), user_addr, base_url)
                msg = f"新增发票，已完成【{numdas - 1}】条，未完成【{num_makeing - numdas + 1}】条，原因：自己看【{base_url}】服务器日志"
            return msg
        except Exception as e:
            return f"{msg}\n{e}"

    def create_budget_template(self, **kwargs):
        """
        创建预算模板
        """
        method_name = "创建预算模板"
        msg = ''
        numdas = 1
        try:
            try:
                cookie = kwargs.get("cookie")
                base_url = kwargs.get("server_addr")
                user_addr = kwargs.get("user_addr")
                r_num = kwargs.get("run_num").strip("^").split("^")
                while len(r_num) < 4:
                    r_num.append(0)
                num_makeing = abs(int(r_num[0]))  # 创建发票的数量
                namedFlag = f"{kwargs.get('named_pre')}" if kwargs.get('named_pre') else ""  # 每笔数据的标记
                if num_makeing <= 0:
                    return f"{method_name} 字段值异常，造数数量需为正整数"
            except:
                return f"{method_name} 字段值异常，造数数量需为正整数"

            # 获取币种信息
            resp = self.base_currency_list(base_url, cookie)
            currenryList = resp.get("page").get("list")
            # 获取预算组织视图信息
            data = "page=1&limit=100&orderField=&order=&lovKey=bgt.bgtViewManagement"
            resp = self.budget_find_datas(base_url, cookie, data)
            viewList = resp.get("page").get("list")

            # 循环新增预算模板
            for _ in range(num_makeing):
                currency = random.choice(currenryList)
                view = random.choice(viewList) if random.randint(0, 1) else {}
                for _ in range(10):
                    resp = self.budget_bgttemplate(base_url, cookie,
                                                   **{
                                                       "dataPre": namedFlag,
                                                       "currency": currency,
                                                       "view": view
                                                   })
                    if "success" in resp.get("msg"):
                        utils.set_cache(base_url, user_addr, utils.get_func_name())
                        numdas += 1
                        break
                    elif _ == 9:
                        return f"{method_name}新增失败，接口响应如下：\n{resp}"
            if numdas >= num_makeing:
                msg = f"{method_name}完成，共【{numdas - 1}】条"
            else:
                dbUtils.write_data_to_db(kwargs.get("task_id"), user_addr, base_url)
                msg = f"{method_name}，已完成【{numdas - 1}】条，未完成【{num_makeing - numdas + 1}】条，原因：自己看【{base_url}】服务器日志"
            return msg
        except Exception as e:
            return f"{msg}\n{e}"
